all files / src/ SpelExpressionParser.js

77.22% Statements 434/562
67.78% Branches 183/270
86.79% Functions 46/53
76.73% Lines 422/550
3 statements Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011                                                            89×     89×     89×     89×     89×     89×     89×                     89× 89× 89× 89× 89× 89× 89× 89×       89×                         125× 125× 38× 38×           36×               34×           119×       127× 127×   127×       131× 131×   131×       135× 135× 135× 27× 27× 27× 27×   27× 24× 24×   22×   20× 10×   10×                           108×       162× 162×       162×       170× 170×             170×       174×     174×     173×       169×       178×     178×                   177×       175×       175× 175× 175× 175× 26×   175× 152×   23×       201× 201× 23×     178×     201× 175×     26× 26×         178×     175×                       23× 23× 23× 23×                                   22× 13×                 62× 55×                                                                                       175× 122×   53×     53× 49×                                                                       53× 40× 40× 40×                                           13×     53× 40× 40× 39×       13×       13× 13× 11×                                                                                   11× 11×                                                                                           75× 53× 53× 53×   46× 46×         22×         52×                                                                       52×     227×     227×                     175× 175×     175×   69×   106×     105×       105× 11×   94× 10×   84× 31×     53×     122×       53×               53×             135× 135× 69×   66× 24×   42×               39×     35× 35×     35×       35×     944×     991× 359×   632× 632× 180×     180×     452×     48×         452×     1073× 347×   726× 726× 726× 1752× 42×     684×     517× 178×   339× 339×     11×     11× 11×     2806×     318×     318×     2196× 69×   2127×                                         39× 39×     39×         48×               252×     33×     89×            
/*
 * Copyright 2002-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/**
 * @author Andy Clement
 * @author Juergen Hoeller
 * @author Ben March
 * @since 0.2.0
 *
 */
 
 
import {TokenKind} from './TokenKind';
import {Tokenizer} from './Tokenizer';
import {BooleanLiteral} from './ast/BooleanLiteral';
import {NumberLiteral} from './ast/NumberLiteral';
import {StringLiteral} from './ast/StringLiteral';
import {NullLiteral} from './ast/NullLiteral';
import {FunctionReference} from './ast/FunctionReference';
import {MethodReference} from './ast/MethodReference';
import {PropertyReference} from './ast/PropertyReference';
import {VariableReference} from './ast/VariableReference';
import {CompoundExpression} from './ast/CompoundExpression';
import {Indexer} from './ast/Indexer';
import {Assign} from './ast/Assign';
import {OpEQ} from './ast/OpEQ';
import {OpNE} from './ast/OpNE';
import {OpGE} from './ast/OpGE';
import {OpGT} from './ast/OpGT';
import {OpLE} from './ast/OpLE';
import {OpLT} from './ast/OpLT';
import {OpPlus} from './ast/OpPlus';
import {OpMinus} from './ast/OpMinus';
import {OpMultiply} from './ast/OpMultiply';
import {OpDivide} from './ast/OpDivide';
import {OpModulus} from './ast/OpModulus';
import {OpPower} from './ast/OpPower';
import {OpInc} from './ast/OpInc';
import {OpDec} from './ast/OpDec';
import {OpNot} from './ast/OpNot';
import {OpAnd} from './ast/OpAnd';
import {OpOr} from './ast/OpOr';
import {OperatorMatches} from "./ast/OperatorMatches";
import {Ternary} from './ast/Ternary';
import {Elvis} from './ast/Elvis';
import {InlineList} from './ast/InlineList';
import {InlineMap} from './ast/InlineMap';
import {Selection} from './ast/Selection';
import {Projection} from './ast/Projection';
 
//not yet implemented
import {OperatorInstanceof} from "./ast/OperatorInstanceof";
import {OperatorBetween} from "./ast/OperatorBetween";
import {TypeReference} from "./ast/TypeReference";
import {BeanReference} from "./ast/BeanReference";
import {Identifier} from "./ast/Identifier";
import {QualifiedIdentifier} from "./ast/QualifiedIdentifier";
import {ConstructorReference} from "./ast/ConstructorReference";
 
export var SpelExpressionParser = function () {
 
 
    var VALID_QUALIFIED_ID_PATTERN = new RegExp('[\\p{L}\\p{N}_$]+');
 
 
    var configuration;
 
    // For rules that build nodes, they are stacked here for return
    var constructedNodes = [];
 
    // The expression being parsed
    var expressionString;
 
    // The token stream constructed from that expression string
    var tokenStream;
 
    // length of a populated token stream
    var tokenStreamLength;
 
    // Current location in the token stream when processing tokens
    var tokenStreamPointer;
 
 
    /**
     * Create a parser with some configured behavior.
     * @param config custom configuration options
     */
    function setConfiguration(config) {
        configuration = config;
    }
 
 
    function parse(expression, context) {
        try {
            expressionString = expression;
            tokenStream = Tokenizer.tokenize(expression);
            tokenStreamLength = tokenStream.length;
            tokenStreamPointer = 0;
            constructedNodes = [];
            var ast = eatExpression();
            if (ImoreTokens()) {
                raiseInternalException(peekToken().startPos, 'MORE_INPUT', nextToken().toString());
            }
            //Assert.isTrue(this.constructedNodes.isEmpty());
            return ast;
        }
        catch (e) {
            throw e.message;
        }
    }
 
    //	expression
    //    : logicalOrExpression
    //      ( (ASSIGN^ logicalOrExpression)
    //	    | (DEFAULT^ logicalOrExpression)
    //	    | (QMARK^ expression COLON! expression)
    //      | (ELVIS^ expression))?;
    function eatExpression() {
        var expr = eatLogicalOrExpression();
        if (moreTokens()) {
            var token = peekToken();
            if (token.getKind() === TokenKind.ASSIGN) {  // a=b
                if (Iexpr === null) {
                    expr = NullLiteral.create(toPosBounds(token.startPos - 1, token.endPos - 1));
                }
                nextToken();
                var assignedValue = eatLogicalOrExpression();
                return Assign.create(toPosToken(token), expr, assignedValue);
            }
 
            if (token.getKind() === TokenKind.ELVIS) {  // a?:b (a if it isn't null, otherwise b)
                if (Iexpr === null) {
                    expr = NullLiteral.create(toPosBounds(token.startPos - 1, token.endPos - 2));
                }
                nextToken();  // elvis has left the building
                var valueIfNull = eatExpression();
                if (IvalueIfNull === null) {
                    valueIfNull = NullLiteral.create(toPosBounds(token.startPos + 1, token.endPos + 1));
                }
                return Elvis.create(toPosToken(token), expr, valueIfNull);
            }
 
            if (token.getKind() === TokenKind.QMARK) {  // a?b:c
                if (Iexpr === null) {
                    expr = NullLiteral.create(toPosBounds(token.startPos - 1, token.endPos - 1));
                }
                nextToken();
                var ifTrueExprValue = eatExpression();
                eatToken(TokenKind.COLON);
                var ifFalseExprValue = eatExpression();
                return Ternary.create(toPosToken(token), expr, ifTrueExprValue, ifFalseExprValue);
            }
        }
        return expr;
    }
 
    //logicalOrExpression : logicalAndExpression (OR^ logicalAndExpression)*;
    function eatLogicalOrExpression() {
        var expr = eatLogicalAndExpression();
        while (peekIdentifierToken('or') || peekTokenOne(TokenKind.SYMBOLIC_OR)) {
            var token = nextToken();  //consume OR
            var rhExpr = eatLogicalAndExpression();
            checkOperands(token, expr, rhExpr);
            expr = OpOr.create(toPosToken(token), expr, rhExpr);
        }
        return expr;
    }
 
    // logicalAndExpression : relationalExpression (AND^ relationalExpression)*;
    function eatLogicalAndExpression() {
        var expr = eatRelationalExpression();
        while (peekIdentifierToken('and') || peekTokenOne(TokenKind.SYMBOLIC_AND)) {
            var token = nextToken();  // consume 'AND'
            var rhExpr = eatRelationalExpression();
            checkOperands(token, expr, rhExpr);
            expr = OpAnd.create(toPosToken(token), expr, rhExpr);
        }
        return expr;
    }
 
    // relationalExpression : sumExpression (relationalOperator^ sumExpression)?;
    function eatRelationalExpression() {
        var expr = eatSumExpression();
        var relationalOperatorToken = maybeEatRelationalOperator();
        if (relationalOperatorToken !== null) {
            var token = nextToken();  // consume relational operator token
            var rhExpr = eatSumExpression();
            checkOperands(token, expr, rhExpr);
            var tk = relationalOperatorToken.kind;
 
            if (relationalOperatorToken.isNumericRelationalOperator()) {
                var pos = toPosToken(token);
                if (tk === TokenKind.GT) {
                    return OpGT.create(pos, expr, rhExpr);
                }
                if (tk === TokenKind.LT) {
                    return OpLT.create(pos, expr, rhExpr);
                }
                if (tk === TokenKind.LE) {
                    return OpLE.create(pos, expr, rhExpr);
                }
                if (tk === TokenKind.GE) {
                    return OpGE.create(pos, expr, rhExpr);
                }
                if (tk === TokenKind.EQ) {
                    return OpEQ.create(pos, expr, rhExpr);
                }
                //Assert.isTrue(tk === TokenKind.NE);
                return OpNE.create(pos, expr, rhExpr);
            }
 
            if (Itk === TokenKind.INSTANCEOF) {
                return OperatorInstanceof.create(toPosToken(token), expr, rhExpr);
            }
 
            if (Etk === TokenKind.MATCHES) {
                return OperatorMatches.create(toPosToken(token), expr, rhExpr);
            }
 
            //Assert.isTrue(tk === TokenKind.BETWEEN);
            return OperatorBetween.create(toPosToken(token), expr, rhExpr);
        }
        return expr;
    }
 
    //sumExpression: productExpression ( (PLUS^ | MINUS^) productExpression)*;
    function eatSumExpression() {
        var expr = eatProductExpression();
        while (peekTokenAny(TokenKind.PLUS, TokenKind.MINUS, TokenKind.INC)) {
            var token = nextToken();//consume PLUS or MINUS or INC
            var rhExpr = eatProductExpression();
            checkRightOperand(token, rhExpr);
            if (token.getKind() === TokenKind.PLUS) {
                expr = OpPlus.create(toPosToken(token), expr, rhExpr);
            }
            else Eif (token.getKind() === TokenKind.MINUS) {
                expr = OpMinus.create(toPosToken(token), expr, rhExpr);
            }
        }
        return expr;
    }
 
    // productExpression: powerExpr ((STAR^ | DIV^| MOD^) powerExpr)* ;
    function eatProductExpression() {
        var expr = eatPowerIncDecExpression();
        while (peekTokenAny(TokenKind.STAR, TokenKind.DIV, TokenKind.MOD)) {
            var token = nextToken();  // consume STAR/DIV/MOD
            var rhExpr = eatPowerIncDecExpression();
            checkOperands(token, expr, rhExpr);
            if (token.getKind() === TokenKind.STAR) {
                expr = OpMultiply.create(toPosToken(token), expr, rhExpr);
            }
            else if (token.getKind() === TokenKind.DIV) {
                expr = OpDivide.create(toPosToken(token), expr, rhExpr);
            }
            else {
                //Assert.isTrue(token.getKind() === TokenKind.MOD);
                expr = OpModulus.create(toPosToken(token), expr, rhExpr);
            }
        }
        return expr;
    }
 
    // powerExpr  : unaryExpression (POWER^ unaryExpression)? (INC || DEC) ;
    function eatPowerIncDecExpression() {
        var expr = eatUnaryExpression(),
            token;
 
        if (peekTokenOne(TokenKind.POWER)) {
            token = nextToken();  //consume POWER
            var rhExpr = eatUnaryExpression();
            checkRightOperand(token, rhExpr);
            return OpPower.create(toPosToken(token), expr, rhExpr);
        }
 
        if (expr !== null && peekTokenAny(TokenKind.INC, TokenKind.DEC)) {
            token = nextToken();  //consume INC/DEC
            if (token.getKind() === TokenKind.INC) {
                return OpInc.create(toPosToken(token), true, expr);
            }
            return OpDec.create(toPosToken(token), true, expr);
        }
 
        return expr;
    }
 
    // unaryExpression: (PLUS^ | MINUS^ | BANG^ | INC^ | DEC^) unaryExpression | primaryExpression ;
    function eatUnaryExpression() {
        var token,
            expr;
 
        if (peekTokenAny(TokenKind.PLUS, TokenKind.MINUS, TokenKind.NOT)) {
            token = nextToken();
            expr = eatUnaryExpression();
            if (Etoken.getKind() === TokenKind.NOT) {
                return OpNot.create(toPosToken(token), expr);
            }
 
            if (token.getKind() === TokenKind.PLUS) {
                return OpPlus.create(toPosToken(token), expr);
            }
            //Assert.isTrue(token.getKind() === TokenKind.MINUS);
            return OpMinus.create(toPosToken(token), expr);
 
        }
        if (peekTokenAny(TokenKind.INC, TokenKind.DEC)) {
            token = nextToken();
            expr = eatUnaryExpression();
            if (token.getKind() === TokenKind.INC) {
                return OpInc.create(toPosToken(token), false, expr);
            }
            return OpDec.create(toPosToken(token), false, expr);
        }
 
        return eatPrimaryExpression();
    }
 
    // primaryExpression : startNode (node)? -> ^(EXPRESSION startNode (node)?);
    function eatPrimaryExpression() {
        var nodes = [];
        var start = eatStartNode();  // always a start node
        nodes.push(start);
        while (maybeEatNode()) {
            nodes.push(pop());
        }
        if (nodes.length === 1) {
            return nodes[0];
        }
        return CompoundExpression.create(toPosBounds(start.getStartPosition(), nodes[nodes.length - 1].getEndPosition()), nodes);
    }
 
    // node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+;
    function maybeEatNode() {
        var expr = null;
        if (peekTokenAny(TokenKind.DOT, TokenKind.SAFE_NAVI)) {
            expr = eatDottedNode();
        }
        else {
            expr = maybeEatNonDottedNode();
        }
 
        if (expr === null) {
            return false;
        }
        else {
            push(expr);
            return true;
        }
    }
 
    // nonDottedNode: indexer;
    function maybeEatNonDottedNode() {
        if (peekTokenOne(TokenKind.LSQUARE)) {
            if (EmaybeEatIndexer()) {
                return pop();
            }
        }
        return null;
    }
 
    //dottedNode
    // : ((methodOrProperty
    //	  | functionOrVar
    //    | projection
    //    | selection
    //    | firstSelection
    //    | lastSelection
    //    ))
    //	;
    function eatDottedNode() {
        var token = nextToken();// it was a '.' or a '?.'
        var nullSafeNavigation = token.getKind() === TokenKind.SAFE_NAVI;
        if (EmaybeEatMethodOrProperty(nullSafeNavigation) || maybeEatFunctionOrVar() || maybeEatProjection(nullSafeNavigation) || maybeEatSelection(nullSafeNavigation)) {
            return pop();
        }
        if (peekToken() === null) {
            // unexpectedly ran out of data
            raiseInternalException(token.startPos, 'OOD');
        }
        else {
            raiseInternalException(token.startPos, 'UNEXPECTED_DATA_AFTER_DOT', toString(peekToken()));
        }
        return null;
    }
 
    // functionOrVar
    // : (POUND ID LPAREN) => function
    // | var
    //
    // function : POUND id=ID methodArgs -> ^(FUNCTIONREF[$id] methodArgs);
    // var : POUND id=ID -> ^(VARIABLEREF[$id]);
    function maybeEatFunctionOrVar() {
        if (!peekTokenOne(TokenKind.HASH)) {
            return false;
        }
        var token = nextToken();
        var functionOrVariableName = eatToken(TokenKind.IDENTIFIER);
        var args = maybeEatMethodArgs();
        if (Eargs === null) {
            push(VariableReference.create(functionOrVariableName.data, toPosBounds(token.startPos, functionOrVariableName.endPos)));
            return true;
        }
 
        push(FunctionReference.create(functionOrVariableName.data, toPosBounds(token.startPos, functionOrVariableName.endPos), args));
        return true;
    }
 
    // methodArgs : LPAREN! (argument (COMMA! argument)* (COMMA!)?)? RPAREN!;
    function maybeEatMethodArgs() {
        if (!peekTokenOne(TokenKind.LPAREN)) {
            return null;
        }
        var args = [];
        consumeArguments(args);
        eatToken(TokenKind.RPAREN);
        return args;
    }
 
    function eatConstructorArgs(accumulatedArguments) {
        if (!peekTokenOne(TokenKind.LPAREN)) {
            raiseInternalException(toPosToken(peekToken()), 'MISSING_CONSTRUCTOR_ARGS');
        }
        consumeArguments(accumulatedArguments);
        eatToken(TokenKind.RPAREN);
    }
 
    /**
     * Used for consuming arguments for either a method or a constructor call
     */
    function consumeArguments(accumulatedArguments) {
        var pos = peekToken().startPos;
        var next;
        do {
            nextToken();  // consume ( (first time through) or comma (subsequent times)
            var token = peekToken();
            if (Itoken === null) {
                raiseInternalException(pos, 'RUN_OUT_OF_ARGUMENTS');
            }
            if (token.getKind() !== TokenKind.RPAREN) {
                accumulatedArguments.push(eatExpression());
            }
            next = peekToken();
        }
        while (next !== null && next.kind === TokenKind.COMMA);
 
        if (Inext === null) {
            raiseInternalException(pos, 'RUN_OUT_OF_ARGUMENTS');
        }
    }
 
    function positionOf(token) {
        if (token === null) {
            // if null assume the problem is because the right token was
            // not found at the end of the expression
            return expressionString.length;
        }
        return token.startPos;
    }
 
    //startNode
    // : parenExpr | literal
    //	    | type
    //	    | methodOrProperty
    //	    | functionOrVar
    //	    | projection
    //	    | selection
    //	    | firstSelection
    //	    | lastSelection
    //	    | indexer
    //	    | constructor
    function eatStartNode() {
        if (maybeEatLiteral()) {
            return pop();
        }
        else Iif (maybeEatParenExpression()) {
            return pop();
        }
        else if (maybeEatTypeReference() || maybeEatNullReference() || maybeEatConstructorReference() || maybeEatMethodOrProperty(false) || maybeEatFunctionOrVar()) {
            return pop();
        }
        else Iif (maybeEatBeanReference()) {
            return pop();
        }
        else Iif (maybeEatProjection(false) || maybeEatSelection(false) || maybeEatIndexer()) {
            return pop();
        }
        else Eif (maybeEatInlineListOrMap()) {
            return pop();
        }
        else {
            return null;
        }
    }
 
    // parse: @beanname @'bean.name'
    // quoted if dotted
    function maybeEatBeanReference() {
        if (IpeekTokenOne(TokenKind.BEAN_REF)) {
            var beanRefToken = nextToken();
            var beanNameToken = null;
            var beanName = null;
            if (peekTokenOne(TokenKind.IDENTIFIER)) {
                beanNameToken = eatToken(TokenKind.IDENTIFIER);
                beanName = beanNameToken.data;
            }
            else if (peekTokenOne(TokenKind.LITERAL_STRING)) {
                beanNameToken = eatToken(TokenKind.LITERAL_STRING);
                beanName = beanNameToken.stringValue();
                beanName = beanName.substring(1, beanName.length() - 1);
            }
            else {
                raiseInternalException(beanRefToken.startPos, 'INVALID_BEAN_REFERENCE');
            }
 
            var beanReference = BeanReference.create(toPosToken(beanNameToken), beanName);
            push(beanReference);
            return true;
        }
        return false;
    }
 
    function maybeEatTypeReference() {
        if (peekTokenOne(TokenKind.IDENTIFIER)) {
            var typeName = peekToken();
            if (EtypeName.stringValue() !== 'T') {
                return false;
            }
            // It looks like a type reference but is T being used as a map key?
            var token = nextToken();
            if (peekTokenOne(TokenKind.RSQUARE)) {
                // looks like 'T]' (T is map key)
                push(PropertyReference.create(token.stringValue(), toPosToken(token)));
                return true;
            }
            eatToken(TokenKind.LPAREN);
            var node = eatPossiblyQualifiedId();
            // dotted qualified id
            // Are there array dimensions?
            var dims = 0;
            while (peekTokenConsumeIfMatched(TokenKind.LSQUARE, true)) {
                eatToken(TokenKind.RSQUARE);
                dims++;
            }
            eatToken(TokenKind.RPAREN);
            push(TypeReference.create(toPosToken(typeName), node, dims));
            return true;
        }
        return false;
    }
 
    function maybeEatNullReference() {
        if (peekTokenOne(TokenKind.IDENTIFIER)) {
            var nullToken = peekToken();
            if (nullToken.stringValue().toLowerCase() !== 'null') {
                return false;
            }
            nextToken();
            push(NullLiteral.create(toPosToken(nullToken)));
            return true;
        }
        return false;
    }
 
    //projection: PROJECT^ expression RCURLY!;
    function maybeEatProjection(nullSafeNavigation) {
        var token = peekToken();
        if (!peekTokenConsumeIfMatched(TokenKind.PROJECT, true)) {
            return false;
        }
        var expr = eatExpression();
        eatToken(TokenKind.RSQUARE);
        push(Projection.create(nullSafeNavigation, toPosToken(token), expr));
        return true;
    }
 
    // list = LCURLY (element (COMMA element)*) RCURLY
    // map  = LCURLY (key ':' value (COMMA key ':' value)*) RCURLY
    function maybeEatInlineListOrMap() {
        var token = peekToken(),
            listElements = [];
 
        if (I!peekTokenConsumeIfMatched(TokenKind.LCURLY, true)) {
            return false;
        }
        var expr = null;
        var closingCurly = peekToken();
        if (IpeekTokenConsumeIfMatched(TokenKind.RCURLY, true)) {
            // empty list '{}'
            expr = InlineList.create(toPosBounds(token.startPos, closingCurly.endPos));
        }
        else Iif (peekTokenConsumeIfMatched(TokenKind.COLON, true)) {
            closingCurly = eatToken(TokenKind.RCURLY);
            // empty map '{:}'
            expr = InlineMap.create(toPosBounds(token.startPos, closingCurly.endPos));
        }
        else {
            var firstExpression = eatExpression();
            // Next is either:
            // '}' - end of list
            // ',' - more expressions in this list
            // ':' - this is a map!
 
            if (IpeekTokenOne(TokenKind.RCURLY)) { // list with one item in it
                listElements.push(firstExpression);
                closingCurly = eatToken(TokenKind.RCURLY);
                expr = InlineList.create(toPosBounds(token.startPos, closingCurly.endPos), listElements);
            }
            else if (peekTokenConsumeIfMatched(TokenKind.COMMA, true)) { // multi item list
                listElements.push(firstExpression);
                do {
                    listElements.push(eatExpression());
                }
                while (peekTokenConsumeIfMatched(TokenKind.COMMA, true));
                closingCurly = eatToken(TokenKind.RCURLY);
                expr = InlineList.create(toPosToken(token.startPos, closingCurly.endPos), listElements);
 
            }
            else Eif (peekTokenConsumeIfMatched(TokenKind.COLON, true)) {  // map!
                var mapElements = [];
                mapElements.push(firstExpression);
                mapElements.push(eatExpression());
                while (peekTokenConsumeIfMatched(TokenKind.COMMA, true)) {
                    mapElements.push(eatExpression());
                    eatToken(TokenKind.COLON);
                    mapElements.push(eatExpression());
                }
                closingCurly = eatToken(TokenKind.RCURLY);
                expr = InlineMap.create(toPosBounds(token.startPos, closingCurly.endPos), mapElements);
            }
            else {
                raiseInternalException(token.startPos, 'OOD');
            }
        }
        push(expr);
        return true;
    }
 
    function maybeEatIndexer() {
        var token = peekToken();
        if (!peekTokenConsumeIfMatched(TokenKind.LSQUARE, true)) {
            return false;
        }
        var expr = eatExpression();
        eatToken(TokenKind.RSQUARE);
        push(Indexer.create(toPosToken(token), expr));
        return true;
    }
 
    function maybeEatSelection(nullSafeNavigation) {
        var token = peekToken();
        if (!peekSelectToken()) {
            return false;
        }
        nextToken();
        var expr = eatExpression();
        if (Iexpr === null) {
            raiseInternalException(toPosToken(token), 'MISSING_SELECTION_EXPRESSION');
        }
        eatToken(TokenKind.RSQUARE);
        if (token.getKind() === TokenKind.SELECT_FIRST) {
            push(Selection.create(nullSafeNavigation, Selection.FIRST, toPosToken(token), expr));
        }
        else if (token.getKind() === TokenKind.SELECT_LAST) {
            push(Selection.create(nullSafeNavigation, Selection.LAST, toPosToken(token), expr));
        }
        else {
            push(Selection.create(nullSafeNavigation, Selection.ALL, toPosToken(token), expr));
        }
        return true;
    }
 
    /**
     * Eat an identifier, possibly qualified (meaning that it is dotted).
     * TODO AndyC Could create complete identifiers (a.b.c) here rather than a sequence of them? (a, b, c)
     */
    function eatPossiblyQualifiedId() {
        var qualifiedIdPieces = [];
        var node = peekToken();
        while (isValidQualifiedId(node)) {
            nextToken();
            if (node.kind !== TokenKind.DOT) {
                qualifiedIdPieces.push(Identifier.create(node.stringValue(), toPosToken(node)));
            }
            node = peekToken();
        }
        if (!qualifiedIdPieces.length) {
            if (node === null) {
                raiseInternalException(expressionString.length(), 'OOD');
            }
            raiseInternalException(node.startPos, 'NOT_EXPECTED_TOKEN', 'qualified ID', node.getKind().toString().toLowerCase());
        }
        var pos = toPosBounds(qualifiedIdPieces[0].getStartPosition(), qualifiedIdPieces[qualifiedIdPieces.length - 1].getEndPosition());
        return QualifiedIdentifier.create(pos, qualifiedIdPieces);
    }
 
    function isValidQualifiedId(node) {
        if (node === null || node.kind === TokenKind.LITERAL_STRING) {
            return false;
        }
        if (node.kind === TokenKind.DOT || node.kind === TokenKind.IDENTIFIER) {
            return true;
        }
        var value = node.stringValue();
        return (value.length && VALID_QUALIFIED_ID_PATTERN.test(value));
    }
 
    // This is complicated due to the support for dollars in identifiers.  Dollars are normally separate tokens but
    // there we want to combine a series of identifiers and dollars into a single identifier
    function maybeEatMethodOrProperty(nullSafeNavigation) {
        if (peekTokenOne(TokenKind.IDENTIFIER)) {
            var methodOrPropertyName = nextToken();
            var args = maybeEatMethodArgs();
            if (args === null) {
                // property
                push(PropertyReference.create(nullSafeNavigation, methodOrPropertyName.stringValue(), toPosToken(methodOrPropertyName)));
                return true;
            }
            // methodreference
            push(MethodReference.create(nullSafeNavigation, methodOrPropertyName.stringValue(), toPosToken(methodOrPropertyName), args));
            // TODO what is the end position for a method reference? the name or the last arg?
            return true;
        }
        return false;
    }
 
    //constructor
    //:	('new' qualifiedId LPAREN) => 'new' qualifiedId ctorArgs -> ^(CONSTRUCTOR qualifiedId ctorArgs)
    function maybeEatConstructorReference() {
        if (IpeekIdentifierToken('new')) {
            var newToken = nextToken();
            // It looks like a constructor reference but is NEW being used as a map key?
            if (peekTokenOne(TokenKind.RSQUARE)) {
                // looks like 'NEW]' (so NEW used as map key)
                push(PropertyReference.create(newToken.stringValue(), toPosToken(newToken)));
                return true;
            }
            var possiblyQualifiedConstructorName = eatPossiblyQualifiedId();
            var nodes = [];
            nodes.push(possiblyQualifiedConstructorName);
            if (peekTokenOne(TokenKind.LSQUARE)) {
                // array initializer
                var dimensions = [];
                while (peekTokenConsumeIfMatched(TokenKind.LSQUARE, true)) {
                    if (!peekTokenOne(TokenKind.RSQUARE)) {
                        dimensions.push(eatExpression());
                    }
                    else {
                        dimensions.push(null);
                    }
                    eatToken(TokenKind.RSQUARE);
                }
                if (maybeEatInlineListOrMap()) {
                    nodes.push(pop());
                }
                push(ConstructorReference.create(toPosToken(newToken), dimensions, nodes));
            }
            else {
                // regular constructor invocation
                eatConstructorArgs(nodes);
                // TODO correct end position?
                push(ConstructorReference.create(toPosToken(newToken), nodes));
            }
            return true;
        }
        return false;
    }
 
    function push(newNode) {
        constructedNodes.push(newNode);
    }
 
    function pop() {
        return constructedNodes.pop();
    }
 
    //	literal
    //  : INTEGER_LITERAL
    //	| boolLiteral
    //	| STRING_LITERAL
    //  | HEXADECIMAL_INTEGER_LITERAL
    //  | REAL_LITERAL
    //	| DQ_STRING_LITERAL
    //	| NULL_LITERAL
    function maybeEatLiteral() {
        var token = peekToken();
        if (Itoken === null) {
            return false;
        }
        if (token.getKind() === TokenKind.LITERAL_INT ||
            token.getKind() === TokenKind.LITERAL_LONG) {
            push(NumberLiteral.create(parseInt(token.stringValue(), 10), toPosToken(token)));
        }
        else if (   token.getKind() === TokenKind.LITERAL_REAL ||
                    token.getKind() === TokenKind.LITERAL_REAL_FLOAT) {
            push(NumberLiteral.create(parseFloat(token.stringValue()), toPosToken(token)));
        }
        else Iif (   token.getKind() === TokenKind.LITERAL_HEXINT ||
                    token.getKind() === TokenKind.LITERAL_HEXLONG) {
            push(NumberLiteral.create(parseInt(token.stringValue(), 16), toPosToken(token)));
        }
        else if (peekIdentifierToken('true')) {
            push(BooleanLiteral.create(true, toPosToken(token)));
        }
        else if (peekIdentifierToken('false')) {
            push(BooleanLiteral.create(false, toPosToken(token)));
        }
        else if (token.getKind() === TokenKind.LITERAL_STRING) {
            push(StringLiteral.create(token.stringValue(), toPosToken(token)));
        }
        else {
            return false;
        }
        nextToken();
        return true;
    }
 
    //parenExpr : LPAREN! expression RPAREN!;
    function maybeEatParenExpression() {
        if (IpeekTokenOne(TokenKind.LPAREN)) {
            nextToken();
            var expr = eatExpression();
            eatToken(TokenKind.RPAREN);
            push(expr);
            return true;
        }
        else {
            return false;
        }
    }
 
    // relationalOperator
    // : EQUAL | NOT_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL | GREATER_THAN
    // | GREATER_THAN_OR_EQUAL | INSTANCEOF | BETWEEN | MATCHES
    function maybeEatRelationalOperator() {
        var token = peekToken();
        if (token === null) {
            return null;
        }
        if (token.isNumericRelationalOperator()) {
            return token;
        }
        if (token.isIdentifier()) {
            var idString = token.stringValue();
            if (IidString.toLowerCase() === 'instanceof') {
                return token.asInstanceOfToken();
            }
            if (EidString.toLowerCase() === 'matches') {
                return token.asMatchesToken();
            }
            if (idString.toLowerCase() === 'between') {
                return token.asBetweenToken();
            }
        }
        return null;
    }
 
    function eatToken(expectedKind) {
        var token = nextToken();
        if (Itoken === null) {
            raiseInternalException(expressionString.length, 'OOD');
        }
        if (Itoken.getKind() !== expectedKind) {
            raiseInternalException(token.startPos, 'NOT_EXPECTED_TOKEN',
                expectedKind.toString().toLowerCase(), token.getKind().toString().toLowerCase());
        }
        return token;
    }
 
    function peekTokenOne(desiredTokenKind) {
        return peekTokenConsumeIfMatched(desiredTokenKind, false);
    }
 
    function peekTokenConsumeIfMatched(desiredTokenKind, consumeIfMatched) {
        if (!moreTokens()) {
            return false;
        }
        var token = peekToken();
        if (token.getKind() === desiredTokenKind) {
            if (consumeIfMatched) {
                tokenStreamPointer++;
            }
            return true;
        }
 
        if (desiredTokenKind === TokenKind.IDENTIFIER) {
            // might be one of the textual forms of the operators (e.g. NE for !== ) - in which case we can treat it as an identifier
            // The list is represented here: Tokenizer.alternativeOperatorNames and those ones are in order in the TokenKind enum
            if (Itoken.getKind().ordinal() >= TokenKind.DIV.ordinal() && token.getKind().ordinal() <= TokenKind.NOT.ordinal() && token.data !== null) {
                // if token.data were null, we'd know it wasn'token the textual form, it was the symbol form
                return true;
            }
        }
        return false;
    }
 
    function peekTokenAny() {
        if (!moreTokens()) {
            return false;
        }
        var token = peekToken();
        var args = Array.prototype.slice.call(arguments);
        for (var i = 0, l = args.length; i < l; i += 1) {
            if (token.getKind() === args[i]) {
                return true;
            }
        }
        return false;
    }
 
    function peekIdentifierToken(identifierString) {
        if (!moreTokens()) {
            return false;
        }
        var token = peekToken();
        return token.getKind() === TokenKind.IDENTIFIER && token.stringValue().toLowerCase() === identifierString.toLowerCase();
    }
 
    function peekSelectToken() {
        if (I!moreTokens()) {
            return false;
        }
        var token = peekToken();
        return token.getKind() === TokenKind.SELECT || token.getKind() === TokenKind.SELECT_FIRST || token.getKind() === TokenKind.SELECT_LAST;
    }
 
    function moreTokens() {
        return tokenStreamPointer < tokenStream.length;
    }
 
    function nextToken() {
        if (ItokenStreamPointer >= tokenStreamLength) {
            return null;
        }
        return tokenStream[tokenStreamPointer++];
    }
 
    function peekToken() {
        if (tokenStreamPointer >= tokenStreamLength) {
            return null;
        }
        return tokenStream[tokenStreamPointer];
    }
 
    function raiseInternalException(pos, message, expected, actual) {
        if (expected) {
            message += '\nExpected: ' + expected;
        }
        if (actual) {
            message += '\nActual: ' + actual;
        }
        throw {
            name: 'InternalParseException',
            message: 'Error occurred while attempting to parse expression \'' + expressionString + '\' at position ' + pos + '. Message: ' + message
        };
    }
 
    function toString(token) {
        if (token.getKind().hasPayload()) {
            return token.stringValue();
        }
        return token.getKind().toString().toLowerCase();
    }
 
    function checkOperands(token, left, right) {
        checkLeftOperand(token, left);
        checkRightOperand(token, right);
    }
 
    function checkLeftOperand(token, operandExpression) {
        if (IoperandExpression === null) {
            raiseInternalException(token.startPos, 'LEFT_OPERAND_PROBLEM');
        }
    }
 
    function checkRightOperand(token, operandExpression) {
        if (IoperandExpression === null) {
            raiseInternalException(token.startPos, 'RIGHT_OPERAND_PROBLEM');
        }
    }
 
    /**
     * Compress the start and end of a token into a single int.
     */
    function toPosToken(token) {
        return (token.startPos << 16) + token.endPos;
    }
 
    function toPosBounds(start, end) {
        return (start << 16) + end;
    }
 
    return {
        setConfiguration: setConfiguration,
        parse: parse
    };
};